package edu.vt.ece3574.ninjatag;

/****************************************************************************
 * Copyright 2012 Landon Biggs, Chris Dusold, Brad Russell, and Craig Wertz	*
 * Licensed under the Apache License, Version 2.0 (the "License");			*
 * you may not use this file except in compliance with the License.			*
 * You may obtain a copy of the License at									*
 * 																			*
 * http://www.apache.org/licenses/LICENSE-2.0								*
 * 																			*
 * Unless required by applicable law or agreed to in writing, software		*
 * distributed under the License is distributed on an "AS IS" BASIS,		*
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.	*
 * See the License for the specific language governing permissions and		*
 * limitations under the License.											*
 ****************************************************************************/

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.Display;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.facebook.android.BaseRequestListener;
import com.facebook.android.FacebookError;
import com.facebook.android.Utility;

public class matchmaking_screen extends Activity implements OnClickListener {

	private Button invite, cancel;
	ProgressDialog dialog;
	private Spinner gameSelect;
	private String gameName;
	private String gameType;
	private EditText gameNameIn;
	private long endTime;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.matchmaking_screen);

		invite = (Button)findViewById(R.id.inviteButton);    
		cancel = (Button)findViewById(R.id.cancelButton);
		invite.setOnClickListener(this);
		cancel.setOnClickListener(this);

		gameNameIn = (EditText)findViewById(R.id.game_name_edittext);

		gameSelect = (Spinner)findViewById(R.id.game_select_spinner);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.game_types, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		gameSelect.setAdapter(adapter);
		gameSelect.setOnItemSelectedListener(new MyOnItemSelectedListener());
		
		gameType = "NinjaTag";

	}

	/*
	 *	The next couple methods are used to override the menu and back physical buttons on the phone.
	 *	onCreateOptionsMenu sets the menu to the custom 'main_menu'
	 *	onOptionsItemSelected starts an activity based on the selected option in the menu
	 * 	onBackPressed sends the app to the previous screen.
	 * 
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu){
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch(item.getItemId() ){

		case R.id.menu_home:
			Intent mainScreenIntent = new Intent(matchmaking_screen.this, group_screen.class);
			startActivity(mainScreenIntent);
			finish();
			break;


		case R.id.menu_map:
			Intent mapScreenIntent = new Intent(matchmaking_screen.this, map_screen.class);
			startActivity(mapScreenIntent);
			finish();
			break;

		case R.id.menu_settings:
			Intent settingsScreenIntent = new Intent(matchmaking_screen.this, settings_screen.class);
			startActivity(settingsScreenIntent);
			finish();
			break;
			
    	case R.id.gps_settings:
    		Intent GPS_ActivityIntent = new Intent(matchmaking_screen.this, GPS_Activity.class);
    		startActivity(GPS_ActivityIntent);
    		finish();
    		break;

		case R.id.menu_lock_or:

			if(getOrientation() == Configuration.ORIENTATION_PORTRAIT){
				this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
				break;
			}

			else if(getOrientation() == Configuration.ORIENTATION_LANDSCAPE){
				this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
				break;
			}
			else Toast.makeText(getBaseContext(), "Error: orientation was not locked", Toast.LENGTH_SHORT).show();
			break;

		case R.id.menu_unlock_or:
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
			break;
		}
		return true;
	}

	@Override
	public void onBackPressed(){
		Intent newIntent = new Intent(matchmaking_screen.this, main_screen.class);
		startActivity(newIntent);
		return;
	}

	@Override
	public void onClick(View v) {

		Intent cancelIntent = new Intent(matchmaking_screen.this, group_screen.class);

		switch(v.getId()){

		case R.id.inviteButton:
			/*dialog = ProgressDialog.show(matchmaking_screen.this, "",
                    "Please wait...", true, true);
            String query = "select name, current_location, uid, pic_square from user where uid in (select uid2 from friend where uid1=me()) AND is_app_user = 1 order by name";
            Bundle params = new Bundle();
            params.putString("method", "fql.query");
            params.putString("query", query);
            Utility.mAsyncRunner.request(null, params,
                    new FriendsRequestListener());*/ // If all went as planned, this is no longer necessary.

			//get name of game from EditText
			gameName = gameNameIn.getText().toString();

			if(gameName.length() > 1){

				if(gameType != null){
					AGame temp = new AGame();
					temp.buildGame(gameName, gameType, endTime);
					
					/**
					 * TODO: add player to game
					 * temp.addPlayer()
					 * 
					 * 
					 */
					
					Utility.mGames.put(gameName, temp);
					
					/*
					 * Temporary.
					 */
					Utility.mGames.addName(gameName);
					

					Intent myIntent = new Intent(matchmaking_screen.this, invite_screen.class);
					startActivity(myIntent);
					finish();
					break;
					
				}
				//toast type
				else Toast.makeText(getBaseContext(), "Select a game type", Toast.LENGTH_SHORT).show();
			}
			else Toast.makeText(getBaseContext(), "Enter a game name", Toast.LENGTH_SHORT).show();
			break;



		case R.id.cancelButton:
			startActivity(cancelIntent);
			finish();
			break;
		}

	}

	/*
	 * callback after friends are fetched via me/friends or fql query.
	 */
	class FriendsRequestListener extends BaseRequestListener {

		@Override
		public void onComplete(final String response, final Object state) {
			dialog.dismiss();
			Intent myIntent = new Intent(getApplicationContext(), invite_screen.class);
			myIntent.putExtra("API_RESPONSE", response);
			startActivity(myIntent);
			finish();
		}

		public void onFacebookError(FacebookError error) {
			dialog.dismiss();
			Toast.makeText(getApplicationContext(), "Facebook Error: " + error.getMessage(),
					Toast.LENGTH_SHORT).show();
		}
	}

	public int getOrientation()
	{
		Display getOrient = getWindowManager().getDefaultDisplay();
		int orientation = Configuration.ORIENTATION_UNDEFINED;
		if(getOrient.getWidth()==getOrient.getHeight()){
			orientation = Configuration.ORIENTATION_SQUARE;
		} else{ 
			if(getOrient.getWidth() < getOrient.getHeight()){
				orientation = Configuration.ORIENTATION_PORTRAIT;
			}else { 
				orientation = Configuration.ORIENTATION_LANDSCAPE;
			}
		}
		return orientation;
	}

	public class MyOnItemSelectedListener implements OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> parent,
				View view, int pos, long id) {
			Toast.makeText(parent.getContext(), parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();

			switch(pos){
			case 0:
				gameType = "NinjaTag";
				break;
			case 1:
				gameType = "Assassination";
			}
		}

		public void onNothingSelected(AdapterView parent) {
			// Do nothing.
		}
	}

}
